package cn.shopifymall.studying.classloader;

import com.sun.xml.internal.ws.util.ByteArrayBuffer;

import java.io.FileInputStream;
import java.security.SecureClassLoader;

/**
 * 重写 findClass 加载 class 文件
 *
 * @Author 孤风雪影
 * @Email gitee.com/efairy520
 * @Date 2025/1/16 11:18
 * @Version 1.0
 */
public class SalaryClassLoader extends SecureClassLoader {

    private String classPath;

    public SalaryClassLoader(String classPath) {
        this.classPath = classPath;
    }

    @Override
    protected Class<?> findClass(String name) {
        String filePath = classPath + name.replace(".", "\\").concat(".myclass");
        FileInputStream fis;
        ByteArrayBuffer ba = new ByteArrayBuffer();
        byte[] b;
        int code;
        try {
            fis = new FileInputStream(filePath);
            int header = fis.read();

            while ((code=fis.read()) != -1) {
                ba.write(code);
            }
            b = ba.toByteArray();
            return this.defineClass(name, b, 0, b.length);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
